<?php

namespace Modules\Admin\Main\Controllers;

use App\Http\Controllers\Controller;
use App\Models\OilCard;
use App\Models\RechargeOrder;
use App\Models\RechargeTask;
use App\Models\ShopOrder;
use function Clue\StreamFilter\append;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class ExcelController extends Controller
{
    //Excel文件导出功能 By Laravel学院
    public function export(Request $request){
        try {
            $value = $request->input("value", false);
            $order_status = $request->input("status");

            $query = ShopOrder::query();
            if (!$value) {
                //查询全部待领取的油卡
                $data = $query->where("order_type", "oil_card")->where("order_status", $order_status)->with('detail')->orderBy('id', 'desc')->get();
            } else {
                $data = $query->where("order_type", "oil_card")->where("order_status", $order_status)->where('created_at', 'like', "%{$value}%")->with('detail')->orderBy('id', 'desc')->get();
            }
            $cellData = [
                ['序号', '卡号', '充值金额', '套餐月份', '快递费', '实付金额', '收件人', '联系电话', '收货地址', '下单时间']
            ];
            if ($data->count() > 0) {
                $i = 1;
                foreach ($data as $k => $v) {
                    //查询充值订单
                    $orderData = RechargeOrder::where("order_sn", $v['order_sn'])->first();
                    if (!$orderData) {
                        continue;
                    }
                    if ($orderData['months'] >= 3) {
                        $money = 0;
                    } else {
                        $money = 10;
                    }
                    $array = [$i, "\t" . $v['detail']['goods_name'] . "\t", $orderData['recharge_amount'], $orderData['months'], $money, $orderData['pay_amount'], $v['username'], $v['phone'], $v['address'], $v['created_at']];
                    array_push($cellData, $array);
                    $i++;
                }
            }
            Excel::create(iconv('UTF-8', 'GBK', $value . '领取油卡用户'), function ($excel) use ($cellData) {
                $excel->sheet('score', function ($sheet) use ($cellData) {
                    $sheet->rows($cellData);
                });
            })->store('xls')->export('xls');

//        $files = storage_path('exports/'.$value.'.xls');
//        $name = basename($files);
//        return response()->download($files, $name ,$headers = ['Content-Type'=>'application/xls;charset=utf-8']);
//        return success(['path'=>storage_path('exports/'.$value.'.xls')]);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }


    public function rechargeOrderExports(){
        try{
            //查询近期待充值的手动订单
            $orderData = RechargeTask::where("recharge_mode",2)->where("status",0)->whereDate("pay_at","<=",date('Y-m-d H:i:s',time()))->orderBy('id','asc')->get();
            if ($orderData->count()){
                $orderArray = [];
                foreach ($orderData as $item){
                    $orderArray[] = $item['recharge_order_id'];
                }
                //去重
                $orderArray = array_unique($orderArray);
                $cellData = [
                    ["序号","订单号","油卡卡号","油卡类型","充值金额","充值月份","支付金额","用户姓名","联系电话","充值类型","充值方式","油卡附属","充值说明","充值状态","充值时间"]
                ];
                //遍历数组
                $i=1;
                foreach ($orderArray as $k=>$v){
                    //查询待充值任务
                    $taskOrder = RechargeTask::where("recharge_order_id",$v)->where("status",0)->with('order')->orderBy('id','asc')->first();
                    //查询油卡
                    $cardData = OilCard::where('card_no',$taskOrder['card_no'])->where('is_company_card',1)->where('status',1)->first();
                    if ($cardData) {
                        $rechargeOrder = RechargeOrder::where("oil_card_id", $cardData['id'])->where("status", '>', 0)->orderBy('id', 'asc')->first();
                        if ($rechargeOrder) {
                            if ($rechargeOrder['id'] == $v) {
                                $remark = "--";
                            } else {
                                $remark = "复充";
                            }
                        }else{
                            $remark = "--";
                        }
                        $company = "公司副卡";
                    }else{
                        $company = "个人油卡";
                        $remark = "--";
                    }

                    if ($taskOrder['card_type']==1){
                        $card_type = "中石化";
                    }else{
                        $card_type = "中石油";
                    }
                    if ($taskOrder['status']==9){
                        $statusName = "充值成功";
                    }elseif ($taskOrder['status']==0){
                        $statusName = "待充值";
                    }elseif ($taskOrder['status']==7){
                        $statusName = "已退款";
                    }else{
                        $statusName = "充值失败";
                    }
                    if ($taskOrder['order']['type']==1){
                        $rechargeType = "--";
                    }else{
                        $rechargeType = "直充";
                    }
                    $item = [$i,$taskOrder['order']['order_sn'],"\t".$taskOrder['card_no']."\t",$card_type,$taskOrder['order']['recharge_amount'],$taskOrder['order']['months'],$taskOrder['order']['pay_amount'],$taskOrder['card_name'],$taskOrder['card_mobile'],$rechargeType,"手动",$company,$remark,$statusName,$taskOrder['pay_at']];
                    array_push($cellData,$item);
                    $i++;
                }
                Excel::create(iconv('UTF-8', 'GBK', date('d').'日待充值用户'), function ($excel) use ($cellData) {
                    $excel->sheet('score', function ($sheet) use ($cellData) {
                        $sheet->rows($cellData);
                    });
                })->store('xls')->export('xls');
            }
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }
}
